package com.mapmymotion;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONException;
import org.json.JSONObject;
import org.jwebsocket.kit.WebSocketException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
//import android.os.Handler;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.mapmymotion.JWC;



public class mainActivity extends MapActivity implements OnInitListener
	 {
//	private MapController mapController;
//	private MapView mapView;
	private LocationManager locationManager;

	
//	private GPSManager gpsManager = null;
	private double speed = 0.0;
	private double altitude = 0.0;
	private double avgSpeed = 0.0;
	private long startTime;
	private long endTime;
	private int measurement_index = Constants.INDEX_KM;
	private AbsoluteSizeSpan sizeSpanLarge = null;
	private AbsoluteSizeSpan sizeSpanSmall = null;
	// private ChatClient myChat;
	SensorManager sensorManager;
	static final int sensor = SensorManager.SENSOR_ORIENTATION;
	protected int orientation;
	// private int TELEMETRY_ID;
	String ns = Context.NOTIFICATION_SERVICE;
	NotificationManager mNotificationManager;
	private TextToSpeech mTts;
	Location lastDestination;
	private int i = 1;
	private double totalDistance = 0.00;
	private String is_memberid;
	private int autostart_interval = 0;
	private int autostop_interval = 0;
	private String myactivitytype = "OTH";
	private int istart = 0;
	private int istop = 0;
	private boolean ib_newactivity = true;
	private int i_interval_list = 0;
	private long ll_priortotaltime = 0;
	private double ld_priordistance = 0.00;
	private static StringBuffer toSend = new StringBuffer("");
	private StringBuffer myInterval = new StringBuffer("");
	private static final String MAP_URL = "http://mapmymotion.com/androidmap.html";
	private WebView webView;
	ListView lv_interval;
	FriendsAdapter friendsAdapter;
	ArrayAdapter<String> intervaladapter;
	private LinearLayout ln;
	private String email;
	private TextView tv_heading;
	Resources res;
	private ProgressBar mProgress;
	// private int mProgressStatus = 0;
	// private Handler mHandler = new Handler();
	private double currentDistance = 0;
	private static Context context;
	private int i_count = 0;
	private String is_error;  // Error message to disply in the dialog
	private String is_message; // Message to display in the dialog
	private int ii_dialogid;  // id of the open Alert dialog

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getApplicationContext();

		setContentView(R.layout.main);

		// getPreferences();

		ln = (LinearLayout) findViewById(R.id.content);
		res = getResources();

		//mapView = (MapView) findViewById(R.id.mapview);
		//mapView.setBuiltInZoomControls(true);
		//mapView.setStreetView(true);
		//mapView.setSatellite(true);
		//mapController = mapView.getController();
		//mapController.setZoom(14); // Zoon 1 is world view

		// Set up Tabs
		TabHost tabs = (TabHost) this.findViewById(R.id.mytabhost);
		tabs.setup();
		// tabs.setOnTabChangedListener((OnTabChangeListener) this);
		TabSpec tspec;
		tspec = tabs.newTabSpec("0").setIndicator("Activity",
				res.getDrawable(R.drawable.ic_tab_activity));
		tspec.setContent(R.id.onoff);
		tabs.addTab(tspec);
		tspec = tabs.newTabSpec("1");
		tspec.setIndicator("Map It", res.getDrawable(R.drawable.ic_tab_maps));
		tspec.setContent(R.id.webview);
		tabs.addTab(tspec);
		tspec = tabs.newTabSpec("2");
		tspec.setIndicator("Friends",
				res.getDrawable(R.drawable.ic_tab_friends));
		tspec.setContent(R.id.webview);
		tabs.addTab(tspec);
		tspec = tabs.newTabSpec("3");
		tspec.setIndicator("History",
				res.getDrawable(R.drawable.ic_tab_activity));

		tspec.setContent(R.id.listview);
		tabs.addTab(tspec);

		setLayout(Constants.TELEMETRY);

		tabs.setOnTabChangedListener(new OnTabChangeListener() {
			// @Override
			public void onTabChanged(String tabId) {

				if (tabId.equals("0")) {
					setLayout(Constants.TELEMETRY);
				}

				else if (tabId.equals("1")) {
					setLayout(Constants.MAPINFO);
				} else if (tabId.equals("2")) {
					setLayout(Constants.FRIENDINFO);

				} else if (tabId.equals("3")) {
					setLayout(Constants.INTERVALINFO);
				}
			}
		});

		// Initialize text-to-speech. This is an asynchronous operation.
		// The OnInitListener (second argument) is called after initialization
		// completes.
		mTts = new TextToSpeech(this, this);

		// set up the chat service
		// myChat = new ChatClient();


		// Load these here as accessing them will be quicker
		getPreferences();
		setupWebView();

		// Get the current activity list
		//myactivitylist = new ActivitiesList();
		//SQLList.getData(Constants.ACTIVITIES,is_memberid);
		//is_message="Loading Activities";
		//new getActivitiesThread(is_message);
		// Get the current Friends list
		// myfriendslist = new FriendsList();
		//is_message="Loading Friends";
		//new getFriendsThread(is_message);
		//SQLList.getData(Constants.FRIENDINFO,is_memberid);

		
		// Set up interval info
		setIntervalInfo();

		JWC.init();
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constants.MINIMUMTIMEBETWEENUPDATES,
				0, new GeoUpdateHandler());


		// Sets Notification icon in status bar
		// setNotification();

	}

	// RESUME
	@Override
	public void onResume() {
		// setNotification();
		getPreferences();

		// Connect to Chat Server
		try {
			if (JWC.isConnected() == false) {
				JWC.open();
			}
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			// TURN ON BUZZ and change color of info box to red
			e.printStackTrace();
		}

		// Set the activity type icon in the info bar
		setActivityDrawable(myactivitytype);

		// Connect the chat client
		// Toast.makeText(this, myChat.setClient(), Toast.LENGTH_SHORT).show();
		// Load these here as accessing them will be quicker
		// Get the current activity list
		// myactivitylist.getData(is_memberid);


		try {
			JWC.getActivities(is_memberid, "0");
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			String is_acceptedoption = "1";
			JWC.getFriends(is_memberid, is_acceptedoption);
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	// ////////////////////////////////////////////////////////
	@Override
	protected void onStop() {

		// If application is about to exit make sure that all data is sent
		if (AppSettings.getUpdateStatus(this) == true
				&& AppSettings.getUpdateInterval(this) == 2) {
			// myChat.sendData(toSend);
			try {
				if (JWC.isConnected() == false) {
					JWC.open();
				}
				JWC.sendaMessage(toSend.toString(), "1");
				toSend.setLength(0);

			} catch (WebSocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// REB mNotificationManager.cancel(TELEMETRY_ID);
		// Don't forget to shutdown!
		if (mTts != null) {
			mTts.stop();
			mTts.shutdown();
		}
		// Toast.makeText(this, myChat.cleanUp(), Toast.LENGTH_SHORT).show();

		try {
			JWC.close();
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		super.onDestroy();
	}

	private void getPreferences() {
		PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		// Shows who is logged in
		email = AppSettings.getEmailAddress(this);
		is_memberid = AppSettings.getMemberid(this);
		if (is_memberid == null || is_memberid.contentEquals("0")) {
			showDialog(Constants.NEWUSER);
			// 20120129 is_memberid =
			// Integer.toString(AppSettings.getmemberid(email));
			// 20120129 AppSettings.setMemberid(this, is_memberid);
		}

		// Get Measurement settings from Preferences
		measurement_index = AppSettings.getUOM(this);
		myactivitytype = AppSettings.getActivityType(this);
		autostart_interval = AppSettings.getAutoStartInterval(this);
		autostop_interval = AppSettings.getAutoStopInterval(this);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		Toast.makeText(mainActivity.this, email, Toast.LENGTH_SHORT).show();
	}

	private void setIntervalInfo() {
		lv_interval = (ListView) findViewById(R.id.interval_list);
		intervaladapter = new ArrayAdapter<String>(this, R.layout.rowlayout,
				R.id.intervalid);
		tv_heading = new TextView(this);
		tv_heading.setTextSize((float) 22d);
		tv_heading.setTypeface(tv_heading.getTypeface(), 1);
		tv_heading.setBackgroundDrawable(res
				.getDrawable(R.drawable.squarebox_input));
		tv_heading.setText("                  Intervals");

		lv_interval.addHeaderView(tv_heading);
		lv_interval.setAdapter(intervaladapter);
	}

	// Implements TextToSpeech.OnInitListener.
	public void onInit(int status) {
		// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
		if (status == TextToSpeech.SUCCESS) {
			// Set preferred language to US english.
			// Note that a language may not be available, and the result will
			// indicate this.
			int result = mTts.setLanguage(Locale.US);
			// Try this someday for some interesting results.
			// int result mTts.setLanguage(Locale.FRANCE);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				// Lanuage data is missing or the language is not supported.
				// Log.e(TAG, "Language is not available.");
			} else {
				// Check the documentation for other possible result codes.
				// For example, the language may be available for the locale,
				// but not for the specified country and variant.

				// The TTS engine has been successfully initialized.
				// Allow the user to press the button for the app to speak
				// again.
				// mAgainButton.setEnabled(true);
				// Greet the user.
				// REMOVE FOR NOW sayMessage("Start Map my Motion");
			}
		} else {
			// Initialization failed.
			// Log.e(TAG, "Could not initialize TextToSpeech.");
		}

	}

	public void ClickHandler(View v) {
		// Toast.makeText(this, "POS:  " + v.getTag(),
		// Toast.LENGTH_LONG).show();
		Integer position = null;
		if (v.getTag() != null) {
			position = Integer.parseInt((String) v.getTag());
		}

		JSONObject json_data = null;
		/*if (position != null && JWC.jArrayFriends != null) {
			try {
				json_data = JWC.jArrayFriends.getJSONObject(position);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}*/

		if (position != null && JWC.getFriends() != null) {
			try {
				json_data = JWC.getFriends().getJSONObject(position);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		switch (v.getId()) {

		case R.id.acceptfriend: // Accept Friend is accepted = 1
			ToggleButton tg_acceptfriend = (ToggleButton) v;
			if (tg_acceptfriend.isChecked()) {
				// tg_addfriend.setTextOn("YANKEE");

				try {
					json_data.put("accepted", 1);
			
					AppSettings.updateFriendStatus(is_memberid,
							json_data.getString("memberid"), "ACC",
							json_data.getString("email"),
							json_data.getString("firstname"),
							json_data.getString("lastname"));

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Toast.makeText(this, "Accept Friend ", Toast.LENGTH_LONG)
						.show();
			} else {
				try {
					json_data.put("accepted", 0);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Toast.makeText(this, "Ignore Friend ", Toast.LENGTH_LONG)
						.show();
			}
			populateFriendsList();
			break;
		case R.id.showfriendbutton: //Friend to view
			ToggleButton tg_showfriend = (ToggleButton) v;
			if (tg_showfriend.isChecked()) {
				try {
					AppSettings.updateFriendStatus(is_memberid,
							json_data.getString("memberid"), "SHO",
							json_data.getString("email"),
							json_data.getString("firstname"),
							json_data.getString("lastname"));
					
					json_data.put("showlocation", 1);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Toast.makeText(this, "Show Friend ", Toast.LENGTH_LONG).show();
			} else {
				try {
					json_data.put("showlocation", 0);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				populateFriendsList();
				Toast.makeText(this, "Hide Friend ", Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.invitebutton:  //Invite Friend
			ToggleButton tg_invite = (ToggleButton) v;
			if (tg_invite.isChecked()) {
				try {
					json_data.put("invited", 1);
			
					AppSettings.updateFriendStatus(is_memberid,
							json_data.getString("memberid"), "INV",
							json_data.getString("email"),
							json_data.getString("firstname"),
							json_data.getString("lastname"));

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Toast.makeText(this, "Invite Friend ", Toast.LENGTH_LONG)
						.show();
			} else {
				try {
					json_data.put("invited", 0);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Toast.makeText(this, "Don't Invite ", Toast.LENGTH_LONG).show();
			}
			populateFriendsList();
			break;

		case R.id.backbutton:
			Toast.makeText(this, "GO BACK ", Toast.LENGTH_LONG).show();
			break;
		case R.id.addfriends:  //Add friends from contacts
			Toast.makeText(this, "Add Friends ", Toast.LENGTH_LONG).show();
			Bundle bundle = new Bundle();
			bundle.putString("myid", is_memberid);

			Intent newIntent = new Intent(mainActivity.this,
					ContactDetail.class);
			newIntent.putExtras(bundle);
			startActivity(newIntent);

			break;
		case R.id.onoff:
			// Do something
			ToggleButton tg = (ToggleButton) v;
			if (tg.isChecked()) {
				// Determine Display items to Show
				istart = 1;
				istop = 0;
				sayMessage("Start");
				setLayout(Constants.TELEMETRY);

			} else {
				sayMessage("Stop");
				istop = 1;
				istart = 0;
				// If Updates are allowed and Update on Stop then send all data
				// to chat server
				// if (AppSettings.getUpdateStatus(this) == true
				// && AppSettings.getUpdateInterval(this) == 2) {
				// myChat.sendData(toSend);
				// }
			}

			break;
		}
		
		//if (position != null && JWC.jArrayFriends != null) {
		//	friendsAdapter.notifyDataSetChanged();
		//	populateFriendsList();
		//}
		if (position != null && JWC.getFriends() != null) {
			//populateFriendsList();
			friendsAdapter.notifyDataSetChanged();
			
		}
		

	}

	// Set the Display Screen Appropriately
	private void setLayout(int i) {
		if (i == Constants.SPLASH) {
			setVisibility(R.id.info, true);
			setVisibility(R.id.info_distance, false);
			setVisibility(R.id.info_pace, false);
			setVisibility(R.id.info_speed, false);
			setVisibility(R.id.info_duration, false);
			setVisibility(R.id.info_avgspeed, false);
		} else if (i == Constants.TELEMETRY) {
			setVisibility(R.id.info, true);
			setVisibility(R.id.listview, false);
			setVisibility(R.id.buttonbar, false);
			// If we have some data then display it
			if (i_interval_list > 0) {
				setVisibility(R.id.interval_list, true);
			} else {
				setVisibility(R.id.interval_list, false);
			}

			if (istart == 0) {
				setVisibility(R.id.info_distance, false);
				setVisibility(R.id.info_pace, false);
				setVisibility(R.id.info_speed, false);
				setVisibility(R.id.info_duration, false);
				setVisibility(R.id.info_avgspeed, false);

			} else {
				setVisibility(R.id.info_distance,
						AppSettings.getDistanceSetting(this));
				setVisibility(R.id.info_pace, AppSettings.getPaceSetting(this));
				setVisibility(R.id.info_speed,
						AppSettings.getCurrentSpeedSetting(this));
				setVisibility(R.id.info_duration,
						AppSettings.getDurationSetting(this));
				setVisibility(R.id.info_avgspeed,
						AppSettings.getAverageSpeedSetting(this));
			}
			ln.setBackgroundDrawable(res.getDrawable(R.drawable.libyadesert));

			setVisibility(R.id.webview, false);
			// setVisibility(R.id.friends, false);
			setVisibility(R.id.empty, false);

			setSpeedText(R.id.info, "Map my Motion Data");
		} else if (i == Constants.MAPINFO) {
			setVisibility(R.id.webview, true);
			setVisibility(R.id.buttonbar, false);
			setVisibility(R.id.info, false);
			// setVisibility(R.id.marker_progress,false);
			setVisibility(R.id.info_distance, false);
			setVisibility(R.id.info_pace, false);
			setVisibility(R.id.info_speed, false);
			setVisibility(R.id.info_duration, false);
			setVisibility(R.id.info_avgspeed, false);
			// setVisibility(R.id.friends, false);
			setVisibility(R.id.interval_list, false);
		} else if (i == Constants.FRIENDINFO) {
			/*
			 * setVisibility(R.id.info, false); setVisibility(R.id.webview,
			 * false); setVisibility(R.id.friends, true);
			 * setVisibility(R.id.info_distance, false);
			 * setVisibility(R.id.info_pace, false);
			 * setVisibility(R.id.info_speed, false);
			 * setVisibility(R.id.info_duration, false);
			 * setVisibility(R.id.info_avgspeed, false);
			 * setVisibility(R.id.interval_list, false); setupFriendsWebView();
			 */
			setVisibility(R.id.webview, false);
			setVisibility(R.id.buttonbar, true);
			setVisibility(R.id.backbutton, false);
			// setVisibility(R.id.headingtext, true);
			setHeadingText(R.id.headingtext, "Friends");
			setVisibility(R.id.addfriends, true);
			setVisibility(R.id.info, false);
			setVisibility(R.id.interval_list, false);
			populateFriendsList();

		} else if (i == Constants.INTERVALINFO) {
			setVisibility(R.id.webview, false);
			setVisibility(R.id.buttonbar, true);
			// setVisibility(R.id.headingtext, true);
			setHeadingText(R.id.headingtext, "Activities");
			setVisibility(R.id.addfriends, false);
			setVisibility(R.id.backbutton, false);
			setVisibility(R.id.info, false);
			setVisibility(R.id.interval_list, false);
			setVisibility(R.id.info_distance, false);
			setVisibility(R.id.info_pace, false);
			setVisibility(R.id.info_speed, false);
			setVisibility(R.id.info_duration, false);
			setVisibility(R.id.info_avgspeed, false);

			populateActivitiesList();

		}
	}

	private void setVisibility(int textid, boolean b) {
		int i = 0; // VISIBLE
		if (b == false) {
			i = 8;
		}
		;// 8 is GONE
		View tv = ((View) findViewById(textid));
		tv.setVisibility(i);
	}

	public void setSpeedText(int textid, String text) {
		Spannable span = new SpannableString(text);
		int firstPos = text.indexOf(32);

		span.setSpan(sizeSpanLarge, 0, firstPos,
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(sizeSpanSmall, firstPos + 1, text.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		TextView tv = ((TextView) findViewById(textid));

		tv.setText(span);

	}

	public void setHeadingText(int textid, String text) {

		TextView tv = ((TextView) findViewById(textid));
		tv.setVisibility(View.VISIBLE);
		tv.setGravity(1);

		tv.setText(text);

	}

	/** Sets up the WebView object and loads the URL of the page **/
	private void setupWebView() {
		webView = (WebView) findViewById(R.id.webview);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient());
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

		webView.setWebViewClient(new WebViewClient() {
			
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// Log.i(TAG, "Processing webview url click...");
				view.loadUrl(url);
				
				return true;
			}
			public void onLoadResource(WebView view, String url) {
				is_message="Loading Maps";
				//showDialog(Constants.MESSAGE);
				
			}

			public void onPageFinished(WebView view, String url) {
				// Log.i(TAG, "Finished loading URL: " +url);
				// if (progressBar.isShowing()) {
				// progressBar.dismiss();
				// }
				//mProgress.setVisibility(View.GONE);
				//dismissDialog(Constants.MESSAGE);
			}

			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {

				is_error=description;
				showDialog(Constants.ERROR);
			}
		});

		webView.loadUrl(MAP_URL + "?myid=" + is_memberid);
		//dismissDialog(Constants.MESSAGE);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean result = true;

		switch (item.getItemId()) {
		case R.id.menu_about: {
			showDialog(Constants.ABOUT);

			break;
		}
		case R.id.preferences: {
			startActivity(new Intent(this, AppSettings.class));
			// setLayout(Constants.TELEMETRY);
			break;
		}

		default: {
			result = super.onOptionsItemSelected(item);

			break;
		}
		}

		return result;
	}

	private double convertSpeed(double speed) {
		return ((speed * Constants.HOUR_MULTIPLIER) * Constants.UNIT_MULTIPLIERS[measurement_index]);
	}

	private double roundDecimal(double value, final int decimalPlace) {
		BigDecimal bd = new BigDecimal(value);

		bd = bd.setScale(decimalPlace, RoundingMode.HALF_UP);
		value = bd.doubleValue();

		return value;
	}

	private void sayMessage(String m) {
		mTts.speak(m, TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in
												// the playback queue.
				null);
	}

	/*
	 * private void setNotification() { mNotificationManager =
	 * (NotificationManager) getSystemService(ns); int icon = R.drawable.mapoff;
	 * CharSequence tickerText = "Map my Motion"; long when =
	 * System.currentTimeMillis();
	 * 
	 * Notification notification = new Notification(icon, tickerText, when);
	 * //Context context = getApplicationContext(); CharSequence contentTitle =
	 * "Map my Motion notification"; CharSequence contentText = "Map my Motion";
	 * Intent notificationIntent = new Intent(this, mainActivity.class);
	 * PendingIntent contentIntent = PendingIntent.getActivity(this,
	 * 0,notificationIntent, Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
	 * notification.setLatestEventInfo(context, contentTitle,
	 * contentText,contentIntent); // notification.defaults |=
	 * Notification.DEFAULT_SOUND; notification.flags |=
	 * Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(TELEMETRY_ID,
	 * notification);
	 * 
	 * }
	 */

	public static Context getContext() {
		return context;
	}

	private void setActivityDrawable(String aactivitytype) {
		// Display the right activity type
		TextView tv = ((TextView) findViewById(R.id.info));
		int i_online = R.drawable.yellowcircle15;
		if (JWC.isConnected()) {
			i_online = R.drawable.online;
		}

		if (aactivitytype.contains("CYC")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bicycle, 0,
					i_online, 0);
		}
		;
		if (aactivitytype.contains("RUN")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.runner, 0,
					i_online, 0);
		}
		if (aactivitytype.contains("WHC")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.wheelchair,
					0, i_online, 0);
		}
		;
		if (aactivitytype.contains("WLK")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.walker, 0,
					i_online, 0);
		}
		if (aactivitytype.contains("SKI")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.skiing, 0,
					i_online, 0);
		}
		if (aactivitytype.contains("SWM")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.swimming, 0,
					i_online, 0);
		}
		if (aactivitytype.contains("OTH")) {
			tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.circle, 0,
					i_online, 0);
		}

	}

	private void populateActivitiesList() {

		int iarraylength;
		ListView listView;
		ArrayList<HashMap<String, String>> jsonactivitieslist = new ArrayList<HashMap<String, String>>();

		jsonactivitieslist.clear();
is_message="Loading Activities";		
showDialog(Constants.MESSAGE);
		listView = (ListView) findViewById(R.id.listview);
		TextView lempty= (TextView) findViewById(R.id.empty);
		lempty.setText(R.string.waitactivities);
		listView.setEmptyView(lempty) ;

		//listView.setEmptyView((TextView) findViewById(R.id.empty));

		LayoutInflater inflater = getLayoutInflater();
		/*View header = inflater.inflate(R.layout.mainrowlist,
				(ViewGroup) findViewById(R.id.header_row_layout));
		header.setBackgroundDrawable(res
				.getDrawable(R.drawable.squarebox_input));

		// listView.addHeaderView(header, null, false);
*/
		mProgress = (ProgressBar) findViewById(R.id.progress);
		mProgress.setVisibility(View.VISIBLE);

		for (int j = 1; j < 60; j++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (JWC.getActivities() != null) {
				iarraylength = JWC.getActivities().length();

				for (int icount = 0; icount < iarraylength; icount++) {
					JSONObject json_data;
					HashMap<String, String> temp = new HashMap<String, String>();
					try {
						json_data = JWC.getActivities().getJSONObject(icount);
						temp.put("activitytype",
								json_data.getString("activitytype"));
						temp.put("localdate", json_data.getString("localdate"));
						temp.put("totaldistance",
								json_data.getString("totaldistance") + "mi");
						jsonactivitieslist.add(temp);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
			ActivitiesAdapter activitiesAdapter = new ActivitiesAdapter(this,
					jsonactivitieslist, R.layout.mainrowlist, new String[] {
							"activitytype", "localdate", "totaldistance" },
					new int[] { R.id.activitytype, R.id.activitydate,
							R.id.totaldistance });
			listView.setAdapter(activitiesAdapter);
			mProgress.setVisibility(View.GONE);
			dismissDialog(Constants.MESSAGE);
			break;
			}
		}
		listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
			public final void onItemClick(AdapterView<?> listView, View cell,
					int position, long id) {
				JSONObject json_data;
				String mystarttime = null;
				String mylocaldate = null;
				Integer lId = -1;
				Integer myid = cell.getId();

				switch (myid) {
				case R.id.header_row_layout: // Do something
												// sayMessage("Start"); break;

					try {
						is_message="Loading Interval Info";
						showDialog(Constants.MESSAGE);
						json_data = JWC.getActivities().getJSONObject(position);
						lId = json_data.getInt("activitysummaryid");
		//				mystarttime = json_data.getString("starttime");
		//				mylocaldate = json_data.getString("localdate");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Bundle bundle = new Bundle();
					bundle.putInt("activitysummaryid", lId);
		//			bundle.putString("myid", is_memberid);
		//			bundle.putString("dte", mystarttime);
		//			bundle.putString("localdte", mylocaldate);


				/*	SQLList.getData(Constants.INTERVALINFO,lId.toString());
					//dismissDialog(Constants.MESSAGE);
					is_message="Loading Geo Point Info";
					//showDialog(Constants.MESSAGE);
					SQLList.getData(Constants.POINTS,lId.toString());
					dismissDialog(Constants.MESSAGE);
				*/
					
					Intent newIntent = new Intent(mainActivity.this,
							ActivityDetail.class);
					newIntent.putExtras(bundle);
					startActivity(newIntent); 
					dismissDialog(Constants.MESSAGE);
				}
			}
		});

	}

		
	private void populateFriendsList() {
		int iarraylength;
		
		ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
		ListView lView;
		int li_sort = -1;
		jsonlist.clear();
		// SQLList.getData(Constants.FRIENDINFO, is_memberid);
		lView = (ListView) findViewById(R.id.listview);
		
		TextView lempty= (TextView) findViewById(R.id.empty);
		lempty.setText(R.string.waitforfriends);
		lView.setEmptyView(lempty) ;
		//lView.setEmptyView((TextView) findViewById(R.id.empty));

		/*
		 * LayoutInflater inflater = getLayoutInflater(); View header =
		 * inflater.inflate(R.layout.friendsrowlist, (ViewGroup)
		 * findViewById(R.id.friends_header_row_layout));
		 * header.setBackgroundDrawable(res
		 * .getDrawable(R.drawable.squarebox_input));
		 * lView.addFooterView(header, null, false); }
		 */
		mProgress = (ProgressBar) findViewById(R.id.progress);
		mProgress.setVisibility(View.VISIBLE);

		for (int j = 1; j < 20; j++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (JWC.getFriends() != null ) {
				iarraylength = JWC.getFriends().length();

				for (int icount = 0; icount < iarraylength; icount++) {
					JSONObject json_data;
					HashMap<String, String> temp = new HashMap<String, String>();
					try {
						json_data = JWC.getFriends().getJSONObject(icount);
						int li_sortorder = json_data.getInt("sortorder");
						if (li_sortorder != li_sort) {
							HashMap<String, String> temphead = new HashMap<String, String>();
							String is_heading = null;
							li_sort = li_sortorder;
							switch (li_sortorder) {

							case 0:
								is_heading = "Invite";
								break;
							case 1:
								is_heading = "Accept Friends";
								break;
							case 2:
								is_heading = "Awaiting Acceptance";
								break;
							case 3:
								is_heading = "Active Friends";
								break;
							}

							temphead.put("fullname", is_heading);
							temphead.put("sortnumber",
									Integer.toString(li_sort));
							temphead.put("positionid", "-1");
							jsonlist.add(temphead);
						}
						// temp.put("firstname",
						// json_data.getString("firstname"));
						// temp.put("lastname",json_data.getString("lastname"));
						// temp.put("accepted",json_data.getString("accepted"));
						temp.put("fullname", json_data.getString("firstname")
								+ " " + json_data.getString("lastname"));
						temp.put("sortnumber", json_data.getString("sortorder"));
						temp.put("positionid", Integer.toString(icount));
						jsonlist.add(temp);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			

			friendsAdapter = new FriendsAdapter(
					this,
					jsonlist,
					R.layout.friendsrowlist,
					// new String[] { "firstname", "lastname","accepted" }, new
					// int[] {
					// R.id.firstname, R.id.lastname,R.id.accepted });
					new String[] { "fullname", "sortnumber", "positionid" },
					new int[] { R.id.fullname, R.id.sortnumber, R.id.positionid });

			lView.setAdapter(friendsAdapter);
			mProgress.setVisibility(View.GONE);
			break;
			}
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		// outState.putString("TEXT", (String)text.getText());
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		// text.setText(savedInstanceState.getString("TEXT"));
	}


	protected Dialog onCreateDialog(int id){
		Dialog dialog = null;
		ii_dialogid=id;
		final View layout;
//		AlertDialog alert;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		Context mContext = getApplicationContext();
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(LAYOUT_INFLATER_SERVICE);

		switch(id){
		case Constants.MESSAGE:
			builder.setTitle("Message");
			builder.setMessage("Please Wait..."+ is_message);
			break;

		case Constants.MAPID:
			builder.setTitle("Activity Map");
			builder.setMessage("Retrieving Map for Activity ID...Please Wait");
			break;
		case Constants.ERROR:
			builder.setTitle("Message");
			builder.setMessage("Error: " + is_error)
			.setPositiveButton("Continue",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.dismiss();
									// mainActivity.this.finish();
								}
							})
							.setNegativeButton("Close",
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int id) {
											dialog.dismiss();
											mainActivity.this.finish();
										}
									});;
				
			break;
		case Constants.ABOUT:

			layout = inflater.inflate(R.layout.about, null);
			builder.setTitle(getString(R.string.app_name));
			builder.setView(layout);

			builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			break;
		case Constants.NEWUSER:
			layout = inflater.inflate(R.layout.newuser,
					(ViewGroup) findViewById(R.id.newuser));

			builder.setView(layout);
			builder.setCancelable(false)
					.setTitle("New User")
					.setPositiveButton("Add User",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									EditText email = ((EditText) layout
											.findViewById(R.id.et_emailaddress));
									EditText p1 = ((EditText) layout
											.findViewById(R.id.et_pw));
									EditText p2 = ((EditText) layout
											.findViewById(R.id.et_pw2));
									EditText fname = ((EditText) layout
											.findViewById(R.id.et_fname));
									EditText lname = ((EditText) layout
											.findViewById(R.id.et_lname));
									TextView error = ((TextView) layout
											.findViewById(R.id.tv_error));
									String is_memberid = Integer.toString(AppSettings
											.newUser(email.getText().toString(), p1
													.getText().toString(), p2
													.getText().toString(), fname
													.getText().toString(), lname
													.getText().toString()));
									error.setText(is_memberid);
									dialog.cancel();
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
									dialog.dismiss();
									// mainActivity.this.finish();
								}
							});
		}

		dialog=builder.create();
		dialog.show();
		return dialog;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	public class GeoUpdateHandler implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			//int lat = (int) (location.getLatitude() * 1E6);
			//int lng = (int) (location.getLongitude() * 1E6);
			//GeoPoint point = new GeoPoint(lat, lng);
			//mapController.animateTo(point); //	mapController.setCenter(point);
			//path.add(point);
			//mapView.getOverlays().clear();
			//mapView.getOverlays().add(new RoutePathOverlay(path));
			// Update the map regardless as to whether the running app is engaged
			final String movemarkerURL = "javascript:moveMarker("
					+ location.getLatitude() + "," + location.getLongitude() + ")";
			webView.loadUrl(movemarkerURL);

			// Get the Current Speed
			speed = location.getSpeed();
			String unitString = (measurement_index == 0) ? "km/h" : "mi/h";

			// If auto start interval is greater than 0 then dont start until the
			// speed is greater
			// than auto start interval in preferences
			if (istart == 0) {
				if (roundDecimal(convertSpeed(speed), 2) < autostart_interval
						&& autostart_interval > 0) {
					setSpeedText(R.id.info, "Auto Start at " + autostart_interval
							+ " " + unitString);
					return;
				} else {
					// setLayout(Constants.TELEMETRY);
					// setSpeedText(R.id.info_avgspeed, "Auto Started");
					ToggleButton b = (ToggleButton) findViewById(R.id.onoff);
					b.performClick();
					// istart = 1;
					return;
				}
			}

			// If speed drops below the setting and activity is started then stop
			// button is pressed
			if (roundDecimal(convertSpeed(speed), 2) <= autostop_interval
					&& autostop_interval > -1 && istop == 0 && istart == 1) {
				ToggleButton b = (ToggleButton) findViewById(R.id.onoff);
				b.performClick();
				return;
			}
			;

			if (istop == 1) {
				return;
			}
			;
			// Get the Altitude
			altitude = location.getAltitude();
			// If auto start interval is greater than 0 then dont start until the
			// speed is greater
			// than auto start interval in preferences
			if (istart == 0) {
				if (roundDecimal(convertSpeed(speed), 2) < autostart_interval) {
					setSpeedText(R.id.info, "Auto Start at " + autostart_interval
							+ " " + unitString);
					return;
				} else {
					// setLayout(Constants.TELEMETRY);
					// setSpeedText(R.id.info_avgspeed, "Auto Started");
					ToggleButton b = (ToggleButton) findViewById(R.id.onoff);
					b.performClick();
					// istart = 1;
					return;
				}
			}

			// String direction = Integer.toString(orientation);
			if (lastDestination == null && location != null) {
				lastDestination = location;
				totalDistance = 0.00;
				startTime = location.getTime();
				return;
			}

			// Need to subtract endTime from startTime and then
			// totalDistance/totalTime
			endTime = location.getTime();
			long totalSeconds = (endTime - startTime) / 1000;

			// Set the Current Speed
			String myCurrentSpeed = String.format("Speed is %4.1f %s",
					convertSpeed(speed), unitString);
			setSpeedText(R.id.info_speed, myCurrentSpeed);

			// Get latest distance
			currentDistance = location.distanceTo(lastDestination);
			totalDistance += currentDistance;
			lastDestination = location;

			// Need to keep from dividing by zero
			if (totalSeconds == 0) {
				totalSeconds = 1;
			}
			;
			avgSpeed = (totalDistance / totalSeconds);
			String myAverageSpeed = String.format("Average Speed is %4.1f %s",
					convertSpeed(avgSpeed), unitString);

			// Set the Avg Speed
			setSpeedText(R.id.info_avgspeed, myAverageSpeed);

			// Set the total Distance
			String myDistance = String.format("Distance is: %.2f %s",
					(totalDistance / Constants.UNITS[measurement_index]),
					(measurement_index == 0) ? "km" : "miles");
			setSpeedText(R.id.info_distance, myDistance);

			// Calculate and display Pace
			double minutespermile = (60 / convertSpeed(avgSpeed));
			if (minutespermile > 100) {
				minutespermile = 0;
			}
			;
			String myPace = AppSettings.getMS(minutespermile);
			setSpeedText(R.id.info_pace, myPace);

			// Calculate and display Duration...Elapsed Time
			String myDuration = AppSettings.getHMS(totalSeconds);
			setSpeedText(R.id.info_duration, myDuration);

			// Calculate interval avg mph and say messages based on the notification
			// interval NOTIFICATIONS
			if (totalDistance >= (AppSettings.getNotificationDistanceInterval(mainActivity.this)
					* Constants.UNITS[measurement_index] * i)
					&& AppSettings.getNotificationDistanceInterval(mainActivity.this) > 0) {
				// Calculate interval settings and display
				long ll_intervaltime = totalSeconds - ll_priortotaltime;
				double ld_intervaldistance = totalDistance - ld_priordistance;
				double ld_intervalspeed = convertSpeed(ld_intervaldistance
						/ ll_intervaltime);

				// Save distance and time for next interval
				ld_priordistance = totalDistance;
				ll_priortotaltime = totalSeconds;
				String ls_intervalpace = AppSettings.getMS(60 / ld_intervalspeed);
				// myInterval.append(ls_intervalpace + ((i % 2 == 0) ? "" : "\t"));
				myInterval.append(String.format("Interval %02d: %5.2f", i,
						ld_intervalspeed) + ((i % 2 == 0) ? "" : "\t"));

				String s = myInterval.toString();

				intervaladapter.insert(s, i_count);

				if (i % 2 == 0) {
					myInterval.delete(0, myInterval.length());
					i_count++;
				}

				/*
				 * //myInterval.append(String.format("Interval %02d: %5.2f", i, //
				 * ld_intervalspeed) + ((i % 2 == 0) ? "" : "\t")); i_interval_list
				 * = myInterval.length(); if (i % 2 == 0) { String s =
				 * myInterval.toString(); myInterval.delete(0, myInterval.length());
				 * intervaladapter.add(s); }
				 */
				// First time thru set Interval based on setting
				if (AppSettings.getIntervalSetting(mainActivity.this) == true && i == 1) {
					setVisibility(R.id.interval_list, true);
				}

				i++;
				// Say the voice notifications selected
				StringBuffer toSay = new StringBuffer("");
				// If pace is below indicated minimum pace tell runner to speed up
				if (minutespermile > AppSettings.getMinPace(mainActivity.this)) {
					toSay.append("Pick up your speed");
				}
				;
				if (AppSettings.getDistanceCue(mainActivity.this) == true) {
					toSay.append(myDistance);
				}
				;
				if (AppSettings.getCurrentSpeedCue(mainActivity.this) == true) {
					toSay.append(myCurrentSpeed);
				}
				;
				if (AppSettings.getAverageSpeedCue(mainActivity.this) == true) {
					toSay.append(myAverageSpeed);
				}
				;
				if (AppSettings.getPaceCue(mainActivity.this) == true) {
					toSay.append(myPace);
				}
				;
				if (AppSettings.getDurationCue(mainActivity.this) == true) {
					toSay.append(myDuration);
				}
				;
				sayMessage(toSay.toString());
			} // END NOTIFICATIONS
				// Prepare Data to send to Chat Server and Send if Continuous update
				// selected
			if (currentDistance < .01) {
				return;
			}
			// Only when first value of the activity is sent
			if (ib_newactivity) {
				// If we have a valid trip then insert an activity summary
				// indicating an activity has begun
				String string2Send = "|ZNW" + "|" + is_memberid + "|" + startTime
						+ "|" + myactivitytype + "\n";
				try {
					if (JWC.isConnected() == false) {
						JWC.open();
					}
					JWC.sendaMessage(string2Send.toString(), "0");

				} catch (WebSocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// myChat.sendData(string2Send);
				toSend.append(string2Send);
				ib_newactivity = false;
			}
			String string2Send = "|TEL" + "|" + is_memberid + "|"
					+ location.getLatitude() + "|" + location.getLongitude() + "|"
					+ location.getTime() + "|" + Double.toString(currentDistance)
					+ "|" + Double.toString(altitude) + "|" + myactivitytype + "\n";
			toSend.append(string2Send);
			if (AppSettings.getUpdateStatus(mainActivity.this) == true
					&& AppSettings.getUpdateInterval(mainActivity.this) == 1) {
				// myChat.sendData(string2Send);

				try {
					if (JWC.isConnected() == false) {
						JWC.open();
					}
					JWC.sendaMessage(string2Send.toString(), "0");
				} catch (WebSocketException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			
			
		}

		@Override
		public void onProviderDisabled(String provider) {
		}

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	
}
	class getActivitiesThread implements Runnable 
 	{
	private String ls_Message="";
	getActivitiesThread(String s_Message) 
	    {
   	        if (s_Message == null) {
	            throw new NullPointerException("s_message");
	        }

	    	ls_Message=s_Message;
	        Thread t=new Thread (this);
	        t. start ( );
	    }
	    
	    public void run () 
	    {
			is_message="Loading Interval Info";
			//showDialog(Constants.MESSAGE);
			SQLList.getData(Constants.ACTIVITIES,is_memberid);
			//dismissDialog(ii_dialogid);
    	    }
	} 
	class getFriendsThread implements Runnable 
 	{
	private String ls_Message="";
	getFriendsThread(String s_Message) 
	    {
   	        if (s_Message == null) {
	            throw new NullPointerException("s_message");
	        }

	    	ls_Message=s_Message;
	        Thread t=new Thread (this);
	        t. start ( );
	    }
	    
	    public void run () 
	    {
			is_message="Loading Interval Info";
			//showDialog(Constants.MESSAGE);
			SQLList.getData(Constants.FRIENDINFO,is_memberid);
			//dismissDialog(ii_dialogid);
    	    }
	} 
	
}
